package stark.app.function.calculator;

import android.content.pm.ActivityInfo;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.lifecycle.ViewModelProvider;

import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.stark.calculator.science.CalKey;
import com.stark.calculator.science.ExpressionViewModel;
import com.stark.calculator.util.CalPrefUtil;

import stark.app.R;
import stark.app.databinding.ActivityScienceCalBinding;
import stark.common.basic.base.BaseNoModelActivity;

/**
 * Author：daizhongbin on 2024/11/7
 * Email：1027154338@qq.com
 * Desc:
 */
public class ScienceCalActivity extends BaseNoModelActivity<ActivityScienceCalBinding> {

    private ExpressionViewModel viewModel;
    //是否为科学计算器的标志
    private boolean isScienceCalculator = false;
    private boolean isVoiceEnabled = CalPrefUtil.isCalVoiceEnabled();

    @Override
    protected int onCreate() {
        //布局文件直接拷贝的别人的，开发写的时候，需要优化的时候则优化
        return R.layout.activity_science_cal;
    }

    @Override
    protected void initView() {
        //设置按钮监听器按钮
        Button[] standardButtons = new Button[]{
                mDataBinding.num0, mDataBinding.num1, mDataBinding.num2, mDataBinding.num3, mDataBinding.num4,
                mDataBinding.num5, mDataBinding.num6, mDataBinding.num7, mDataBinding.num8, mDataBinding.num9,
                mDataBinding.btnDot, mDataBinding.btnEqual, mDataBinding.btnAdd, mDataBinding.btnMinus,
                mDataBinding.btnMultiply, mDataBinding.btnDivide, mDataBinding.btnClear, mDataBinding.leftBracket,
                mDataBinding.rightBracket, mDataBinding.btnDelete,
                mDataBinding.reciprocal, mDataBinding.MClear, mDataBinding.MAdd, mDataBinding.MSub, mDataBinding.MR,
                mDataBinding.sqr, mDataBinding.cube, mDataBinding.power, mDataBinding.factorial, mDataBinding.squareRoot,
                mDataBinding.powerRoot, mDataBinding.euler, mDataBinding.pi, mDataBinding.ln, mDataBinding.log, mDataBinding.sin,
                mDataBinding.cos, mDataBinding.tan, mDataBinding.percent, mDataBinding.inverse, mDataBinding.Rad
        };
        //为每个按钮添加点击事件
        for (Button btn : standardButtons) {
            if (btn != null) {
                btn.setOnClickListener(this);
            }
        }
        mDataBinding.ivMore.setOnClickListener(v -> {
            showMoreMenu();
        });
        isScienceCalculator = CalPrefUtil.isScienceCalculator();
        mDataBinding.getRoot().post(() -> {
            if (isScienceCalculator) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT);
            }
        });
    }

    @Override
    protected void initData() {
        viewModel = new ViewModelProvider(this).get(ExpressionViewModel.class);
        CalSpeaker speaker = new CalSpeaker();
        speaker.enabled(isVoiceEnabled);
        viewModel.setSpeaker(speaker);
        viewModel.getContentLiveData().observe(this, expression -> mDataBinding.ShowText.setText(expression));
        viewModel.getCalRetLiveData().observe(this, ret -> mDataBinding.resultText.setText(ret));
        viewModel.getInverseLiveData().observe(this, inverse -> {
            if (inverse) {
                setViewText(mDataBinding.ln, com.stark.calculator.R.string.cal_ln_inverse);
                setViewText(mDataBinding.log, com.stark.calculator.R.string.cal_log_inverse);
                setViewText(mDataBinding.sin, com.stark.calculator.R.string.cal_sin_inverse);
                setViewText(mDataBinding.cos, com.stark.calculator.R.string.cal_cos_inverse);
                setViewText(mDataBinding.tan, com.stark.calculator.R.string.cal_tan_inverse);
            } else {
                setViewText(mDataBinding.ln, com.stark.calculator.R.string.cal_ln);
                setViewText(mDataBinding.log, com.stark.calculator.R.string.cal_log);
                setViewText(mDataBinding.sin, com.stark.calculator.R.string.cal_sin);
                setViewText(mDataBinding.cos, com.stark.calculator.R.string.cal_cos);
                setViewText(mDataBinding.tan, com.stark.calculator.R.string.cal_tan);
            }
        });
        viewModel.getRadLiveData().observe(this, rad -> {
            if (rad) {
                setViewText(mDataBinding.Rad, com.stark.calculator.R.string.cal_Deg);
                setViewText(mDataBinding.State1, com.stark.calculator.R.string.cal_Rad);
            } else {
                setViewText(mDataBinding.Rad, com.stark.calculator.R.string.cal_Rad);
                setViewText(mDataBinding.State1, com.stark.calculator.R.string.cal_Deg);
            }
        });

        if (isScienceCalculator) {
            //科学计算器（横屏）
            setViewText(mDataBinding.State1, viewModel.isRad() ? com.stark.calculator.R.string.cal_Rad : com.stark.calculator.R.string.cal_Deg);
            setViewText(mDataBinding.StateMemory, viewModel.isMemoryEmpty() ? "" : "M");
        }
    }

    @Override
    protected void onClickCallback(View v) {
        Object tag = v.getTag();
        if (tag == null) return;

        if (tag instanceof String) {
            CalKey calKey = CalKey.getCalKeyByValue((String) tag);
            if (calKey == null) return;
            viewModel.handleClickCalKey(calKey);
            if (calKey == CalKey.MC) {
                mDataBinding.StateMemory.setText("");
            } else if (calKey == CalKey.M_ADD || calKey == CalKey.M_MINUS) {
                mDataBinding.StateMemory.setText("M");
            }
        }
    }

    private void setViewText(TextView textView, String text) {
        if (textView != null) {
            textView.setText(text);
        }
    }

    private void setViewText(TextView textView, int strId) {
        setViewText(textView, getString(strId));
    }

    private void showMoreMenu() {
        String[] menuTextArray = new String[]{
                isScienceCalculator ? "标准计算器" : "科学计算器",
                "历史记录",
                isVoiceEnabled ? "关闭声音" : "打开声音"
        };
        new XPopup.Builder(this)
                .atView(mDataBinding.ivMore)
                .asAttachList(menuTextArray, null, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        if (position == 0) {
                            CalPrefUtil.setScienceCalculatorOrNot(!isScienceCalculator);
                            setRequestedOrientation(isScienceCalculator ? ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);
                        } else if (position == 1) {
                            //历史记录
                            startActivity(CalRecordActivity.class);
                        } else {
                            isVoiceEnabled = !isVoiceEnabled;
                            CalPrefUtil.setCalVoiceEnabledOrNot(isVoiceEnabled);
                            viewModel.getSpeaker().enabled(isVoiceEnabled);
                        }
                    }
                })
                .show();
    }

}
